import fs from 'node:fs'
import path from 'node:path'

function defaultTest(fileName: string, route: string) {
  const fileReg = /yi\.(?:js|ts)$/
  if (fileReg.test(fileName)) {
    return route
  }
}

export default function loadFile({ controllerDir = '', test = defaultTest } = {} as { controllerDir: string, test?: (fileName: string, route: string) => string | undefined }) {
  if (!controllerDir || !fs.existsSync(controllerDir)) {
    throw new Error(`service目录未设置或 ${controllerDir} 不存在`)
  }
  const controllerMap = {} as Record<string, {
    path: string
    file: string
    handler: any
    fullUrl: string
  }>
  function listDir(dir: string, route: string) {
    const fileList = fs.readdirSync(dir, 'utf-8')
    for (let i = 0; i < fileList.length; i++) {
      const PATH = path.join(dir, fileList[i])
      const stat = fs.lstatSync(PATH)

      if (stat.isDirectory()) {
        const routePath = `${route}/${fileList[i]}`
        listDir(PATH, routePath)
      }
      else {
        const basename = path.basename(PATH)

        // 正则判断是否是以.js或.ts结尾
        const finalPath = test!(basename, route)
        if (finalPath) {
          loadRoute(PATH, finalPath, `${finalPath}/${basename}`)
        }
      }
    }
  }

  function loadRoute(routeFile: string, routePath: string, fullUrl: string) {
    // eslint-disable-next-line ts/no-require-imports
    let file = require(routeFile)
    if (file.__esModule) file = file.default
    controllerMap[routePath] = {
      path: routePath,
      handler: file,
      file: routeFile,
      fullUrl,
    }
  }
  return function () {
    listDir(controllerDir, '')

    return controllerMap
  }
}
